package com.ff.ticket.controller;


import com.ff.ticket.domain.User;
import com.ff.ticket.service.impl.UserService;
import com.ff.ticket.util.Coder;
import com.ff.ticket.util.RandomValidateCodeUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口", notes = "用户登录")
    public Map<String, Object> loginUser(@ApiParam(required = true, value = "登录帐号") @RequestParam String account,
                                         @ApiParam(required = true, value = "登录密码") @RequestParam String password,
                                         HttpServletRequest request) throws Exception {

        Map<String, Object> result = new HashMap<>();
        User user = userService.findUserByAccount(account);
        if (null != user) {
            //String pw = Coder.encryptMD5(password);
            String pw = Coder.encryptMD5_(password);
            System.out.println(pw);
            if (user.getPassword().equals(pw)) {
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("loginUser", account);
                //httpSession.setAttribute("auth", groupAuthService.findGroupAuthByGroupName(user.getGroup()));
                result.put("code", 10000);
                result.put("message", "登录成功");
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("token", user.getAccount());
                result.put("data", data);
            } else {
                result.put("code", 10001);
                result.put("message", "密码错误");
            }
        } else {
            result.put("code", 10002);
            result.put("message", "用户不存在");
        }
        return result;
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getverify")
    @ApiOperation(value = "生成验证码", notes = "生成验证码")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            System.out.println("获取验证码失败>>>>   ");
        }
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getverify2")
    @ApiOperation(value = "生成验证码", notes = "生成验证码")
    public void getVerify2(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            System.out.println("获取验证码失败>>>>   ");
        }
    }

    /**
     * 忘记密码页面校验验证码
     */
    @PostMapping(value = "/checkverify")
    @ApiOperation(value = "验证验证码", notes = "验证验证码")
    public Map<String, Object> checkVerify(@ApiParam(required = true, value = "图形验证码") @RequestParam String imgCode,
                                           HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            //从session中获取随机数
            String random = (String) request.getSession().getAttribute("RANDOMVALIDATECODEKEY");
            if (random == null) {
                result.put("code", 10001);
                result.put("message", "验证码已失效");
            }
            if (random.equals(imgCode)) {
                result.put("code", 10000);
                result.put("message", "验证码验证成功");
            } else {
                result.put("code", 10002);
                result.put("message", "图形验证码错误");
            }
        } catch (Exception e) {
            System.out.println("验证码校验失败");
            result.put("code", 10002);
            result.put("message", "图形验证码错误");
        }
        return result;
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户退出接口", notes = "用户退出")
    public Map<String, Object> loginUser(HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();
        HttpSession httpSession = request.getSession();
        httpSession.removeAttribute("loginUser");
        result.put("code", 10000);
        return result;
    }

    @PostMapping("/changename")
    @ApiOperation(value = "根据帐号修改姓名", notes = "修改姓名")
    public Map<String, Object> changeNameByAccount(@ApiParam(required = true, value = "帐号") @RequestParam String account,
                                                   @ApiParam(required = true, value = "新姓名") @RequestParam String newName) throws Exception {

        Map<String, Object> result = new HashMap<>();

        User user = userService.findUserByAccount(account);
        if (null != user) {
            user.setName(newName);
            userService.updateUser(user);
            result.put("code", 10000);
        } else {
            result.put("code", 10001);
            result.put("message", "根据帐号修改姓名失败");
        }

        return result;

    }

    @PostMapping("/changepw")
    @ApiOperation(value = "用户修改密码接口", notes = "修改密码")
    public Map<String, Object> changePassword(@ApiParam(required = true, value = "旧密码") @RequestParam String oldpassword,
                                              @ApiParam(required = true, value = "新密码") @RequestParam String newpassword,
                                              HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();

        HttpSession httpSession = request.getSession();
        String loginUser = (String) httpSession.getAttribute("loginUser");
        User user = userService.findUserByAccount(loginUser);

        if (null != user && null != oldpassword) {
            String pw = Coder.encryptMD5_(oldpassword);
            if (user.getPassword().equals(pw)) {
                user.setPassword(Coder.encryptMD5_(newpassword));
                userService.updateUser(user);
                result.put("message", "密码修改完成");
                result.put("code", 10000);
            } else {
                result.put("code", 10001);
                result.put("message", "旧密码验证失败");
            }


        } else {
            result.put("code", 10001);
            result.put("message", "修改密码失败");
        }

        return result;
    }


    @PostMapping("/createaccount")
    @ApiOperation(value = "管理员创建帐号", notes = "创建新账号(权限角色=admin才可以创建)，默认密码123456，也可以手动填入，角色必须选择一个")
    public Map<String, Object> createNewAccount(@ApiParam(required = true, value = "帐号") @RequestParam String account,
                                                @ApiParam(required = false, value = "默认密码") @RequestParam(required = false) String password,
                                                @ApiParam(required = false, value = "姓名") @RequestParam(required = false) String name,
                                                @ApiParam(required = false, value = "用户组/角色") @RequestParam(required = false) String role,
                                                HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();

        logger.info("createaccount");
        String defaultPassword = "123456";

        HttpSession httpSession = request.getSession();
        String loginUser = (String) httpSession.getAttribute("loginUser");

        User newUser = new User();
        newUser.setAccount(account);
        //设置密码
        if (null != password && password.length() > 0) {
            newUser.setPassword(Coder.encryptMD5_(password));
        } else {
            newUser.setPassword(Coder.encryptMD5_(defaultPassword));
        }
        if (null != name && name.length() > 0) {
            newUser.setName(name);
        }

        if (null != role && role.length() > 0) {
            newUser.setRole(role);
        }
        newUser.setCreatedBy(loginUser);
        userService.updateUser(newUser);
        result.put("code", 10000);

        return result;
    }

}
